'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path')
import * as gameAPI from "@/ipc/gameAPI";
import * as tonwebAPI from "@/ipc/tonwebAPI";
import Axios from 'axios'
import { HttpsProxyAgent } from 'https-proxy-agent';

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
}

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {

      // Required for Spectron testing
      enableRemoteModule: !!process.env.IS_TEST,

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: true,
      // contextIsolation: false,
      sandbox: false,
      nodeIntegrationInWorker: true,
      allowRunningInsecureContent: false, // 允许运行不安全的内容（如不检查SSL）
      webSecurity: false, // 禁用web安全性
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  // register ipc
  // console.log("registerOnIpcMain")
  gameAPI.registerOnIpcMain()
  tonwebAPI.registerOnIpcMain()

  // add custom header
  const filter = {
    urls: ['https://api.hamsterkombatgame.io/*', 'https://api.prod.piggypiggy.io/*']
  }
  const refferList = {
    hamsterkombatgame: "https://hamsterkombatgame.io/",
    piggypiggy: "https://restaurant-v2.piggypiggy.io",
  }
  win.webContents.session.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    const url = details.url
    let reffer = null

    for (const key in refferList) {
      if (Object.prototype.hasOwnProperty.call(refferList, key)) {
        if (url.match(key) != null) {
          const value = refferList[key];
          reffer = value
        }
      }
    }
    details.requestHeaders['User-Agent'] = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
    details.requestHeaders['Referer'] = reffer
    callback({ requestHeaders: details.requestHeaders })
  })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  return win
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()

  // background可以使用storeSession+proxy，但是StringSession+proxy就不行
  // const storeSession = new StoreSession("16096403913")
  // console.log(strSession instanceof Session)
  // const client = new TelegramClient(storeSession, 25741918, "f11ba9726f64ace5ec3b9c40903daf02", {
  //   connectionRetries: 3,
  //   useWSS: false,
  //   timeout: 20,
  //   proxy: {
  //     ip: "103.177.238.224", // Proxy host (IP or hostname)
  //     port: 6401, // Proxy port
  //     username: 'jkyeytls',
  //     password: 'm46r6yilb1gc',
  //     MTProxy: false, // Whether it's an MTProxy or a normal Socks one
  //     socksType: 5, // If used Socks you can choose 4 or 5.
  //     timeout: 2, // Timeout (in seconds) for connection,
  //   },
  // })
  // try {
  //   await client.connect()
  //   const isAuth = await client.checkAuthorization()
  //   if (isAuth) {
  //     const msgs = await client.getMessages(undefined, {
  //       limit: 1,
  //       search: "Login code:"
  //     })
  //     if (msgs != null && msgs.length > 0) {
  //       const loginCodeMsg = msgs[0]
  //       const date = new Date(loginCodeMsg.date * 1000)
  //       const dateStr = date.toLocaleString()
  //       this.$message({
  //         type: "info",
  //         message: dateStr + "\n" + loginCodeMsg.text,
  //       })
  //     } else {
  //       throw new Error("未收到任何验证码消息")
  //     }
  //   } else {
  //     // account.session = null
  //     // this.$store.dispatch("updateAccount", account)
  //     throw new Error("该账号登录已失效");
  //   }
  // } catch (error) {
  //   console.error(error)
  // } finally {
  //   await client.disconnect()
  //   await client.destroy()
  // }
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
